package com.fenghongzhang.lib_core.base

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import com.fenghongzhang.lib_core.state.Failed
import com.fenghongzhang.lib_core.state.Loading
import com.fenghongzhang.lib_core.state.RequestEvent
import com.fenghongzhang.lib_core.state.Success
import com.fenghongzhang.lib_core.utils.ToastUtils
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.supervisorScope

/**
 *@author Wcj
 *@description
 *@date 2022/6/16 13:41
 */
abstract class BaseFragment<VM : BaseViewModel, VDB : ViewDataBinding> : Fragment() {
    protected abstract val mLayoutResId: Int
    protected lateinit var mBinding: VDB
    protected abstract val mViewModel: VM
    protected lateinit var mParentView: View

    open val mPageCanBack: Boolean = true
    val mCanBack: Boolean
        get() {
            if (mPageCanBack) {
                return mPageCanBack
            }
            val fragments = childFragmentManager.fragments
            if (fragments.isEmpty()) {
                return mPageCanBack
            } else {
                for (fragment in fragments) {
                    if (fragment is BaseFragment<*, *>) {
                        Log.d("pressBack", "child fragment :${fragment} -- ${fragment.isVisible} -- ${fragment.mPageCanBack}")
                        if (fragment.isVisible) {
                            return fragment.mPageCanBack
                        }
                    }
                }
            }
            return mPageCanBack
        }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        mBinding = DataBindingUtil.inflate(layoutInflater, mLayoutResId, container, false)
        mBinding.lifecycleOwner = viewLifecycleOwner
        mParentView = mBinding.root
        return mParentView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initListener()
        initData()
    }

    open fun setLoadingViewVisible(show: Boolean, msg: String = "") {
        if (activity is BaseActivity<*, *>) {
            (requireActivity() as BaseActivity<*, *>).setLoadingViewVisible(show, msg)
        }
    }

    fun hideSoftKeyBoard(view: View) {
        if (activity is BaseActivity<*, *>) {
            (requireActivity() as BaseActivity<*, *>).hideKeyboard(view)
        }
    }

    // 添加通用的状态监听，这里只做Loading的隐藏，显示和错误消息Toast
    open fun addCommonStateListener(stateListener: SharedFlow<RequestEvent>) {
        stateListener.observeWithLifecycle(this, Lifecycle.State.STARTED) {
            when (it) {
                is Success -> {
                    setLoadingViewVisible(false)
                }
                is Loading -> {
                    setLoadingViewVisible(true)
                }
                is Failed -> {
                    ToastUtils.showShort(requireActivity(), it.message)
                    setLoadingViewVisible(false)
                    onLoadFailed(it.message)
                }
                else -> {}
            }
        }
    }

    open fun onLoadFailed(msg: String) {}

    abstract fun initView()

    abstract fun initListener()

    abstract fun initData()

    override fun onDestroy() {
        super.onDestroy()
        if (activity is BaseActivity<*, *>) {
            (requireActivity() as BaseActivity<*, *>).setLoadingViewVisible(false)
        }
    }


}
